package com.managedBean;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Properties;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.SocialAuthUtil;

import com.managedBean.registration.LoginManagedBean;
import com.utils.JsfUtils;

@ManagedBean(name = "userSession")
@SessionScoped
public class UserSessionBean implements Serializable {
	private SocialAuthManager manager;
	private String originalURL;
	private String providerID;
	private Profile profile;

	public UserSessionBean() {
	}

	public void socialConnect() throws Exception {
		// Put your keys and secrets from the providers here
		Properties props = System.getProperties();
		props.put("graph.facebook.com.consumer_key", "1447626468801777");
		props.put("graph.facebook.com.consumer_secret",
				"4090f3feb286d29caaa00ac73cf5c728");
		// Define your custom permission if needed
		props.put("graph.facebook.com.custom_permissions",
				"publish_stream,email,user_birthday,user_location,offline_access");
		// Initiate required components
		SocialAuthConfig config = SocialAuthConfig.getDefault();
		config.load(props);
		manager = new SocialAuthManager();
		manager.setSocialAuthConfig(config);
		// 'successURL' is the page you'll be redirected to on successful login
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();
		String successURL = "http://localhost:8080/PF/pages/ui/socialLoginSuccess.jsf";
		String authenticationURL = manager.getAuthenticationUrl(providerID,
				successURL);
		System.out.println("authentication URL"+authenticationURL);
		pullUserInfo();
		FacesContext.getCurrentInstance().getExternalContext()
				.redirect(authenticationURL);
	}

	public void pullUserInfo() {
		try {
			// Pull user's data from the provider
			ExternalContext externalContext = FacesContext.getCurrentInstance()
					.getExternalContext();
			HttpServletRequest request = (HttpServletRequest) externalContext
					.getRequest();
			Map map = SocialAuthUtil.getRequestParametersMap(request);
			if (this.manager != null) {
				AuthProvider provider = manager.connect(map);
				this.profile = provider.getUserProfile();
				// Do what you want with the data (e.g. persist to the database,
				// etc.)
				System.out.println("User's Social profile: " + profile);
				// Redirect the user back to where they have been before logging
				// in
				LoginManagedBean loginManagedBean = (LoginManagedBean) JsfUtils
				.getBeanInstanceFromFacesContext("login");
				loginManagedBean.facebookLogin(profile);
				FacesContext.getCurrentInstance().getExternalContext()
						.redirect("home.jsf");
			} else
				FacesContext
						.getCurrentInstance()
						.getExternalContext()
						.redirect("home.jsf");
		} catch (Exception ex) {
			System.out.println("UserSession - Exception: " + ex.toString());
		}
	}

	public void logOut() {
		try {
			// Disconnect from the provider
			manager.disconnectProvider(providerID);
			// Invalidate session
			ExternalContext externalContext = FacesContext.getCurrentInstance()
					.getExternalContext();
			HttpServletRequest request = (HttpServletRequest) externalContext
					.getRequest();
//			this.invalidateSession(request);
			// Redirect to home page
			FacesContext
					.getCurrentInstance()
					.getExternalContext()
					.redirect(
							externalContext.getRequestContextPath()
									+ "home.xhtml");
		} catch (IOException ex) {
			System.out.println("UserSessionBean - IOException: "
					+ ex.toString());
		}
	}
	// Getters and Setters

	/**
	 * @return the manager
	 */
	public SocialAuthManager getManager() {
		return manager;
	}

	/**
	 * @param manager the manager to set
	 */
	public void setManager(SocialAuthManager manager) {
		this.manager = manager;
	}

	/**
	 * @return the originalURL
	 */
	public String getOriginalURL() {
		return originalURL;
	}

	/**
	 * @param originalURL the originalURL to set
	 */
	public void setOriginalURL(String originalURL) {
		this.originalURL = originalURL;
	}

	/**
	 * @return the providerID
	 */
	public String getProviderID() {
		return providerID;
	}

	/**
	 * @param providerID the providerID to set
	 */
	public void setProviderID(String providerID) {
		this.providerID = providerID;
	}

	/**
	 * @return the profile
	 */
	public Profile getProfile() {
		return profile;
	}

	/**
	 * @param profile the profile to set
	 */
	public void setProfile(Profile profile) {
		this.profile = profile;
	}
}
